package br.com.massai.controller.filter;

import java.io.IOException;
import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import javax.servlet.http.HttpSession;

import br.com.massai.model.entity.Usuario;
import br.com.massai.view.utils.FacesUtil;
import br.com.massai.view.utils.NavigationUtil;

@Named("controleAcesso")
@SessionScoped
public class ControleAcesso implements Serializable {

	private static final long serialVersionUID = -2419787857887789936L;

	private Usuario usuario;

	public ControleAcesso() { }
	
	public HttpSession obterSession(){
		return (HttpSession) FacesUtil.obterFacesContext().getExternalContext().getSession(false);
	}
	
	public Usuario login(String login, String senha){
		Usuario user = new Usuario(); //TODO verifica LOGIN no DAO
		if(user != null && user.getId() != null){
			this.usuario = user;
			return usuario;
		}
		return null;
	}
	
	public void logout() throws IOException {
		invalidateSession();
		NavigationUtil.toLogin();
	}
	
	public String nomeUsuarioLogado(){
		if(loggedIn())
			return getUsuario().getNome();
		return null;
	}

	public static void invalidateSession(){
		FacesUtil.obterFacesContext().getExternalContext().invalidateSession();
	}

	public boolean loggedIn(){
		return usuario != null;
	}
	
	public Usuario getUsuario(){
		return usuario;
	}

	public void setUsuario(Usuario user){
		this.usuario = user;
	}
}
